<template>
  <div class="project-registration">
    <h1 class="title">New Project Registration / 新项目注册</h1>

    <!-- 基本信息 -->
    <h2 class="section-title">Project Information / 基本信息</h2>
    <el-form :model="project" :rules="rules" ref="projectForm" label-width="120px">
      <div ref="pdfContent" id="pdfContent">
        <el-form-item label="Title / 题目" prop="title">
          <el-input v-model="project.title"></el-input>
        </el-form-item>
        <el-form-item label="Abstract or Description / 摘要或介绍" prop="abstractDescription">
          <el-input type="textarea" v-model="project.abstractDescription" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="Subject / 项目学科" prop="subject">
          <el-checkbox-group v-model="project.subject">
            <el-checkbox label="Architecture / 建筑"></el-checkbox>
            <el-checkbox label="Arts and Humanities / 艺术与人文"></el-checkbox>
            <el-checkbox label="Business / 商业"></el-checkbox>
            <el-checkbox label="Education / 教育"></el-checkbox>
            <el-checkbox label="Engineering / 工程"></el-checkbox>
            <el-checkbox label="Law / 法律"></el-checkbox>
            <el-checkbox label="Life Science / 生命科学"></el-checkbox>
            <el-checkbox label="Medicine and Health Science / 医学与健康科学"></el-checkbox>
            <el-checkbox label="Physical Sciences and Mathematics / 物理科学与数学"></el-checkbox>
            <el-checkbox label="Social and Behavioral Science / 社会科学"></el-checkbox>
            <el-checkbox label="Others / 其他"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 主要负责人表单项 -->
        <!-- 主要负责人表单项 -->
        <el-form-item label="Primary Investigator / 负责人" :prop="'investigators[0].surname'">
          <el-input v-model="project.investigators[0].surname" placeholder="Surname / 姓"></el-input>
          <el-input v-model="project.investigators[0].givenName" placeholder="Given Name / 名"></el-input>
          <el-input v-model="project.investigators[0].email" placeholder="Email / 电子邮箱"></el-input>
          <el-input v-model="project.investigators[0].telephone" placeholder="Telephone / 电话"></el-input>
          <el-input v-model="project.investigators[0].affiliation" placeholder="Affiliation / 单位"></el-input>
        </el-form-item>

        <!-- 其他负责人表单项 -->
        <el-form-item label="Primary Investigator / 负责人" v-for="(Investigator, index) in project.investigators" :key="index">
          <el-input :v-model="Investigator.surname" :placeholder="'Surname / 姓'"></el-input>
          <el-input :v-model="Investigator.givenName" :placeholder="'Given Name / 名'"></el-input>
          <el-input :v-model="Investigator.email" :placeholder="'Email / 电子邮箱'"></el-input>
          <el-input :v-model="Investigator.telephone" :placeholder="'Telephone / 电话'"></el-input>
          <el-input :v-model="Investigator.affiliation" :placeholder="'Affiliation / 单位'"></el-input>
          <el-button v-show="index === 0" type="text" @click="addContact">Add Contact / 添加联系人</el-button>
          <el-button v-show="index !== 0" type="text" @click="removeContact(index)">Remove Contact / 移除联系人</el-button>
        </el-form-item>

        <el-form-item label="Project Location / 项目开展地点">
          <el-input v-model="project.location" placeholder="Country or Region / 国家或地区"></el-input>
        </el-form-item>
        <el-form-item label="Project Start Date / 项目开始时间">
          <el-date-picker
              v-model="project.startDate"
              type="date"
              placeholder="Select date / 选择日期"
              :picker-options="datePickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="Project End Date / 项目结束时间">
          <el-date-picker
              v-model="project.endDate"
              type="date"
              placeholder="Select date / 选择日期"
              :picker-options="datePickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="Project Registration Status / 注册时项目情况" prop="registrationStatus">
          <el-radio-group v-model="project.registrationStatus">
            <el-radio label="Registration prior to creation of data / 注册在数据生成之前"></el-radio>
            <el-radio
                label="Registration prior to any human observation of the data / 注册在任何人为观测之前"></el-radio>
            <el-radio label="Registration prior to accessing the data / 注册在数据获得之前"></el-radio>
            <el-radio label="Registration prior to analysis of the data / 注册在数据分析之前"></el-radio>
            <el-radio label="Registration following analysis of the data / 注册在数据分析之后"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="Explanation of Existing Data and Registration / 解释注册状态"
                      prop="registrationExplanation">
          <el-input type="textarea" v-model="project.registrationExplanation" :rows="4"></el-input>
        </el-form-item>
        <div class="section-title">项目细节/Project Details</div>
        <el-form-item label="研究计划/Study Design" prop="studyDesign">
          <el-input type="textarea" v-model="project.studyDesign" :rows="6"></el-input>
        </el-form-item>
        <el-form-item label="干预方法/Intervention" prop="intervention">
          <el-input type="textarea" v-model="project.intervention" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="随机方法/Randomization" prop="randomization">
          <el-input type="textarea" v-model="project.randomization" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="主要结果/Primary outcome" prop="primaryOutcome">
          <el-input v-model="project.primaryOutcome"></el-input>
        </el-form-item>
        <el-form-item
            label="主要结果解释：如果主要结果变量是构造或组合生成的/Primary outcome explanation, if outcomes will be constructed"
            prop="primaryOutcomeExplanation">
          <el-input type="textarea" v-model="project.primaryOutcomeExplanation" :rows="6"></el-input>
        </el-form-item>
        <el-form-item label="其他结果/Other outcomes" prop="otherOutcomes">
          <el-input type="textarea" v-model="project.otherOutcomes" :rows="6"></el-input>
        </el-form-item>
        <el-form-item label="数据收集过程/Data collection procedure" prop="dataCollectionProcedure">
          <el-input type="textarea" v-model="project.dataCollectionProcedure" :rows="6"></el-input>
        </el-form-item>
        <el-form-item label="样本规模/Sample size" prop="sampleSize">
          <el-input type="textarea" v-model="project.sampleSize" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="样本原理及解释/Sample size rationale" prop="sampleSizeRationale">
          <el-input type="textarea" v-model="project.sampleSizeRationale" :rows="6"></el-input>
        </el-form-item>

        <div class="section-title">伦理审核/Institutional Review Boards (IRB)</div>
        <el-form-item label="此项是否已获得伦理审核结果/Did you obtain IRB approval for this project"
                      prop="irbApproval">
          <el-radio-group v-model="project.irbApproval">
            <el-radio label="是/Yes"></el-radio>
            <el-radio label="否/No"></el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="section-title">分析计划/Analysis Plan</div>
        <el-form-item
            label="分析计划：请列出此项目将如何进行分析，比如所要使用的统计方法或模型/Analysis Plan: Please describe how the project will be analyzed, including the statistical methods or models that will be used."
            prop="analysisPlan">
          <el-input type="textarea" v-model="project.analysisPlan" :rows="6"></el-input>
        </el-form-item>
      </div>

      <el-form-item>

        <el-button type="primary" @click="updateDraft">update / 修改</el-button>
        <el-button type="primary" @click="generatePDF">导出PDF到本地</el-button>

      </el-form-item>

    </el-form>


  </div>

</template>

<script>
import html2pdf from 'html2pdf.js';

export default {
  name: 'ProjectForm',

  data() {
    return {
      project: {
        userId:0,
        title: '1',
        updateUser: '',
        abstractDescription: '1',
        subject: [],
        investigators:[{
          surname: '0',
          givenName: '0',
          email: '00',
          telephone: '0',
          affiliation: '0'
        }],
        location: '1',
        startDate: null,
        endDate: null,
        registrationStatus: '1',
        registrationExplanation: '1',
        studyDesign: '1',
        intervention: '1',
        randomization: '1',
        primaryOutcome: '1',
        primaryOutcomeExplanation: '1',
        otherOutcomes: '1',
        dataCollectionProcedure: '1',
        sampleSize: '1',
        sampleSizeRationale: '1',
        irbApproval: 'true',
        analysisPlan: '1'
      },
      previewMode: false,
      rules: {
        title: [
          { required: true, message: 'Please enter the project title', trigger: 'blur' }
        ],
        abstractDescription: [
          { required: true, message: 'Please enter the abstract description', trigger: 'blur' },
          { max: 1000, message: 'The abstract description should not exceed 1000 characters', trigger: 'blur' }
        ],
        subject: [
          { required: true, message: 'Please select at least one subject', trigger: 'change' }
        ],
        Investigator: [
          {
            validator: (rule, value, callback) => {
              if (value.length === 0 || value.some(item => Object.values(item).some(val => val === ''))) {
                callback(new Error('Please fill in all fields for the primary investigator'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        location: [
          { required: true, message: 'Please enter the location', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: 'Please select the start date', trigger: 'change' }
        ],
        endDate: [
          {
            validator: (rule, value, callback) => {
              if (this.project.startDate && value && value <= this.project.startDate) {
                callback(new Error('The end date should be after the start date'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        registrationStatus: [
          { required: true, message: 'Please enter the registration status', trigger: 'blur' }
        ],
        registrationExplanation: [
          {
            validator: (rule, value, callback) => {
              if (this.project.registrationStatus && !value) {
                callback(new Error('Please provide an explanation for the registration status'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        studyDesign: [
          { required: true, message: 'Please enter the study design', trigger: 'blur' }
        ],
        intervention: [
          { required: true, message: 'Please enter the intervention', trigger: 'blur' }
        ],
        randomization: [
          { required: true, message: 'Please enter the randomization', trigger: 'blur' }
        ],
        primaryOutcome: [
          { required: true, message: 'Please enter the primary outcome', trigger: 'blur' }
        ],
        primaryOutcomeExplanation: [
          { required: true, message: 'Please provide an explanation for the primary outcome', trigger: 'blur' }
        ],
        otherOutcomes: [
          { required: true, message: 'Please enter the other outcomes', trigger: 'blur' }
        ],
        dataCollectionProcedure: [
          { required: true, message: 'Please enter the data collection procedure', trigger: 'blur' }
        ],
        sampleSize: [
          { required: true, message: 'Please enter the sample size', trigger: 'blur' }
        ],
        sampleSizeRationale: [
          { required: true, message: 'Please provide a rationale for the sample size', trigger: 'blur' }
        ],
        irbApproval: [
          { required: true, message: 'Please indicate whether IRB approval is obtained', trigger: 'change' }
        ],
        analysisPlan: [
          { required: true, message: 'Please enter the analysis plan', trigger: 'blur' }
        ]
      },
      datePickerOptions: {
        disabledDate(date) {
          return date && date < Date.now() - 8.64e7; // Disable dates before today
        }
      }
    }
  },


  created() {
    let _this=this
    axios.get('http://localhost:8082/projects/findById/'+_this.$route.query.id).then(resp=>{
      _this.project=resp.data.data;
      console.log(_this.project)
    })
    _this.project.id=_this.$route.query.id;

  },

  methods: {


    generatePDF() {
      const pdfContent = this.$refs.pdfContent;
      // 内容转换为 PDF 并保存
      html2pdf().from(pdfContent).save();
    },



    addContact() {
      this.project.investigators.push({
        surname: '',
        givenName: '',
        email: '',
        telephone: '',
        affiliation: ''
      });
    },
    removeContact(index) {
      this.project.investigators = this.project.investigators.filter((_, i) => i !== index);
    },

    deleteConfirmation() {
      this.$confirm('Are you sure you want to clean the entire form?', 'Warning', {
        confirmButtonText: 'clean',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        this.project.title = '';
        this.project.abstractDescription = '';
        this.project.subject = [];
        this.project.Investigator = [];
        this.project.location = '';
        this.project.startDate = null;
        this.project.endDate = null;
        this.project.registrationStatus = '';
        this.project.registrationExplanation = '';
        this.project.studyDesign = '';
        this.project.intervention = '';
        this.project.randomization = '';
        this.project.primaryOutcome = '';
        this.project.primaryOutcomeExplanation = '';
        this.project.otherOutcomes = '';
        this.project.dataCollectionProcedure = '';
        this.project.sampleSize = '';
        this.project.sampleSizeRationale = '';
        this.project.irbApproval = '';
        this.project.analysisPlan = '';
      }).catch(() => {
        // 取消操作
      });
    },
    updateDraft() {
      this.project.userId= JSON.parse(localStorage.getItem('access-admin')).id
      this.project.updateUser= JSON.parse(localStorage.getItem('access-admin')).nickname
      console.log(this.userId)
      let _this = this;
      if (this.$refs.projectForm.validate()) {
        axios.post("http://localhost:8082/projects/updateDraft", _this.project).then(resp => {
          if(resp.data.code===200){
            this.$notify.success({
              title :"成功",
              type :"success",
              message :"保存成功",
            })
          }
        })
      }
    },
    exportToPdf() {
      // 获取要导出的页面内容的HTML元素
      const content = document.getElementById("pdfContent");
      // 定义PDF选项，设置页面大小为A4
      const options = {
        filename: "exported.pdf",
        pagebreak: { mode: "css", before: ".page-break" }, // 页面分页
        jsPDF: {
          format: "a4",
          margin: { top: 40, right: 40, bottom: 40, left: 40 },
        },
      };
      console.log(options)
      let _this=this
      // 使用html2pdf.js生成PDF
      // html2pdf().set(options).from(content).save();
      html2pdf().set(options).from(content).output("blob").then(function(pdfBlob) {
        // 创建FormData对象
        const formData = new FormData();
        console.log(pdfBlob)
        // 将PDF Blob添加到FormData
        formData.append("file", pdfBlob,"expored.pdf");
        console.log(formData)


        let admin=JSON.parse(localStorage.getItem('access-admin'));
        let id=admin.id;

        let title=_this.project.title
        formData.append('id', id);
        formData.append('title', title);
        axios.post('http://localhost:8082/projects/uploadPDF',formData)
            .then(response => {

              if (response.data.code === 200) {
                _this.$message({
                  message:"文件链接是："+ response.data.data,
                  type: 'success'
                });
                console.log(response.data.data);
              }
              if (response.data.code === 500) {
                _this.$message.error(response.data.msg);
              }
            })
            .catch(error => {
              console.error(error);
            });
      });

    },


  },





}

</script>

<style>
h1, h2 {
  font-weight: bold;
  font-size: 24px;
}

.section-title {
  margin-top: 20px;
  margin-bottom: 10px;
}

.project-registration {
  margin-bottom: 20px;
}

.form-buttons {
  margin-top: 20px;
}

.save-btn,
.preview-btn,
.delete-btn {
  margin-right: 10px;
}

.preview-mode {
  background-color: #f8f8f8;
  border: 1px solid #ccc;
  padding: 20px;
  margin-top: 20px;
}
</style>